package cn.edu.zafu.bigdata.hdb;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class FileAppendAndRead {
    // 追加内容到文件的方法
    public static void appendToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
            writer.newLine(); // 添加一个新行
            writer.write(content);
        } catch (IOException e) {
            System.out.println("追加到文件时发生错误: " + e.getMessage());
        }
    }

    // 读取文件内容的方法
    public static void readFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        String rootDir = System.getProperty("user.dir");
        System.out.println("程序根目录: " + rootDir);
        System.out.print("请输入要追加的文本：");
        String inputText = scanner.nextLine();

        String fileName = rootDir + "/files/202202010321.txt";
        appendToFile(fileName, inputText); // 将用户输入的文本追加到文件

        System.out.println("文件内容如下：");
        readFile(fileName); // 读取并显示文件内容

        scanner.close();
    }
}
